<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/13
 * Time: 15:34
 */

namespace app\mobile\controller;


use app\Model\AaModel;
use app\Model\CartModel;
use app\Model\CommentModel;
use app\Model\CommodityClassifyModel;
use app\Model\CommodityItemModel;
use app\Model\CommoditySpecModel;
use app\Model\GoodsAttrModel;
use app\Model\GoodsCollectModel;
use app\Model\GoodsImagesModel;
use app\Model\GoodsModel;
use app\Model\OrderActionModel;
use app\Model\OrderGoodsModel;
use app\Model\OrderModel;
use app\Model\PluginModel;
use app\Model\RegionModel;
use app\Model\ShippingAreaModel;
use app\Model\SpecGoodsPriceModel;
use app\Model\UserAddressModel;
use app\Model\UserLeverModel;
use app\Model\UsersModel;
use app\Model\CouponModel;
use app\Model\CouponListModel;
use app\Model\AccountLogModel;
//use function GuzzleHttp\default_user_agent;
use think\Controller;
use think\Db;

//分类页
class Classify extends Common
{
    /*
     * 分类页
     */
    public function index(){
        //商品一级分类
        $data['Comm1'] =CommodityClassifyModel::where('is_show','=',1)->where('delete_time',null)
            ->where('parent_id','=',0)
            ->order('sort_order')
            ->select();
        //商品全部分类
        $Comm2=CommodityClassifyModel::where('is_show','=',1)->where('delete_time',null)->select();
        $data2 = $this->shu($Comm2->toArray(),$data['Comm1']->toArray());
        $data['Comms']=$data2;
//        dump($data2);die();

        return view('index',$data);
    }
    /*
 * 生成无限树形数组
 * $arr 总数据
 * $array 母目录数据（调用本方法放最大一层目录）
 *        重复调用时填该层的数据
     * $id = 该数据主键
 */
    public function shu($arr,$array,$id='id')
    {
        $data=$array;
        foreach ($array as $k=>$v){
            $data2=[];
            foreach ($arr as $key=>$value){
                if ($value['parent_id']==$v[$id]){//找到子目录（follow_id指向母目录id）
                    array_push($data2,$value);//把目录放入母目录的"menu"下
                    $data2 = $this->shu($arr,$data2,$id);
                    $data[$k]['menu']=$data2;
//                    unset($data[$key]);
                }
            }
        }

        return $data;
    }


    /*
     *商品详情页
     */
    public function goodsinfo()
    {

        $getData=input('get.');//传商品id
//        $getData['id']=57;//模拟id
        $where=['goods_id'=>$getData['id']];
        //商品
        $data['goods']=GoodsModel::find($getData['id']);
        if (!$data['goods']){
            $this->error('商品不存在');
        }
        //商品相册（轮播图）
        $data['goods_images'] = GoodsImagesModel::where($where)->select();
        //评价
        $commt = CommentModel::where('parent_id','=',0)
            ->where($where)
            ->select();
        foreach ($commt as $k=>$v){
            if ($v->img!=''){//用户晒图
               $imgs= explode(',',$v->img);
                $commt[$k]['imgs']=$imgs;
            }
            $commt[$k]['admin_comment']=CommentModel::where('parent_id','=',$v->comment_id)->select();//管理员回复
            $commt[$k]['headimg']=UsersModel::find($v->user_id)->value('head_pic');
        }
        $data['comment'] = $commt;//用户评论
//        $comms = CommentModel::where($where)->select()->toArray();
//        $data['comment'] = $this->shu($comms,$commt,'comment_id');//暂无追评，
        $data['comment_count']=count($data['comment']);
        //会员折扣
        $data['user_lever']=UserLeverModel::order('discount','desc')->select();
        //商品规格
        //默认规格商品
        $getSpecGoods=SpecGoodsPriceModel::where($where)->select();
        $data['spec_goods']='';
        if (isset($getSpecGoods[0])){//有规格商品
            //1、商品规格类别
            $data['spec_goods']=$getSpecGoods;
            $goodsItem= explode('-',$getSpecGoods[0]->key);
            $data['spec']=CommoditySpecModel::where('type_id','=',$data['goods']->spec_type)->select();
            foreach ($data['spec'] as $k=>$v){
                $item=  CommodityItemModel::where('spec_id','=',$v->s_id)->column('item','id');
                $data['spec'][$k]['item']=$item;

                $data['spec'][$k]['itemd']=$goodsItem;
        }
        }
        //商品付款数
        $data['goods_num']=OrderGoodsModel::where($where)->sum('goods_num');
        //商品属性
        $data['goodAttr']=GoodsAttrModel::alias('g_a')->where('g_a.goods_id','=',$getData['id'])
            ->join('commodity_attribute c_a','g_a.attr_id=c_a.attr_id')
            ->order('c_a.order','asc')
            ->select();

        //是否收藏
        $data['collect']=GoodsCollectModel::where($where)
            ->where('user_id','=',session('user.user_id'))
            ->find();
//        dump($data['comment']->toArray());die();

//        $data['scale']=CartModel::where('user_id',session('user.user_id'))->count('id');
        return view('goodsinfo',$data);
    }


    /*
     *  商品加入购物车
     */
    public function ajaxAddCart()
    {
        if (!(session('?user'))){//如果没有登陆
            return retJson('',250,'请先登陆');
        }
        $getData = input('post.');
//        ["goods_add"] => string(1) "6"
//       ["goods_id"] => string(2) "50"
        $getGoods=GoodsModel::find($getData['goods_id']);//商品信息
        //购物车
        $where=[
            'goods_id'=>$getGoods->goods_id,
            'user_id'=>session('user.user_id'),
        ];
        if (isset($getData["item"])){//有规格属性的商品
            //从小到大
            asort($getData["item"]);
            $item['spec_key']= implode('-',$getData["item"]);

            $specGoodsPrice=SpecGoodsPriceModel::where([ 'goods_id'=>$getGoods->goods_id,'key'=>$item['spec_key']])->find();
            if (!$specGoodsPrice||$specGoodsPrice->store_count<$getData['goods_add']){//该规格存在
                return retJson('',201,'很抱歉，现在库存不足');
            }
            $where['spec_key']=$item['spec_key'];

            $item['spec_key_name']=$specGoodsPrice->key_name;
        }
        $getCart = CartModel::where($where)->find();
        if ($getCart){//如果购物车已有
            $setCart = CartModel::where($where)->setInc('goods_num',$getData['goods_add']);//添加该物的数量
        }else{
            $insert=[
                'user_id'=>session('user.user_id'),
                'goods_id'=>$getGoods->goods_id,
                'goods_sn'=>$getGoods->goods_sn,
                'goods_name'=>$getGoods->goods_name,
//                'market_price'=>$getGoods->market_price,//市场价
//                'goods_price'=>$getGoods->shop_price,//本店价
//                'member_goods_price'=>$getGoods->shop_price*session('user.discount'),//会员优惠价
                'goods_num'=>$getData['goods_add'],
                'add_time'=>time(),
            ];
            if (isset($getData["item"])) {//有规格属性的商品
//                $insert['goods_price']=$specGoodsPrice->price;//规格价（替换本店价）
//                $insert['member_goods_price']=$specGoodsPrice->price*session('user.discount');//会员优惠价
                $insert['spec_key']=$item['spec_key'];//规格键名
                $insert['spec_key_name']=$item['spec_key_name'];//规格键中文描述
            }
            $setCart = CartModel::insert($insert);
        }
        return setDatabase($setCart,'加入购物车');

    }

    /*
     * 购物车页
     */
    public function shoppingtrolley()
    {
        $this->yanz();//  判断是否登陆

//        dump(session('user'));
        return view('shoppingtrolley');
    }

    /*
     *  判断是否登陆
     */
    public function emplogin()
    {
        if (!(session('?user'))){//如果没有登陆
            $this->redirect('Login/login');
        }
    }

    /*
     * 购物车最新页
     */
    public function shopplist()
    {

        //购物车数据
        $getData= input('post.');
        $update=[];
        $Cart = new CartModel();
        if (isset($getData['goods_num'])){//购物车改变购买数量
            foreach ($getData['goods_num'] as $k=>$v){
                if (isset($getData['cart_select'][$k])){
                    $where1 = ['id'=>$k,'selected'=>1];
                }else{
                    $where1 = ['id'=>$k,'selected'=>0];
                }
                array_push($update,$where1);
                $where2=['id'=>$k,'goods_num'=>$v];
                array_push($update,$where2);
            }
            $Cart->saveAll($update);
        }
        if (isset($getData['ids'])){//删除
            $Cart->destroy($getData['ids']);
        }
//        $where=['user_id'=>session('user.user_id')];
        $data['cartList']=$this->shopping_trolley();//购物车选中商品的具体属性
//        dump($data['cartList']->toArray());die();
        //计算选中的物品价格
        $data['total_price']['total_fee']=$this->calculate(session('user.user_id'));//总价
        return view('shopplist',$data);
    }
    /*
     * 购物车选中商品的具体属性（价格、数量、图片地址等）
     */
    public function shopping_trolley()
    {
        $data=CartModel::
              where(['user_id'=>session('user.user_id')])
            ->order('add_time','desc')
            ->select();
        foreach ($data as $k=>$v){
            $where=['goods_id'=>$v->goods_id];
            //商品图片路径
            $moneyq= GoodsModel::where($where)->find();//默认商品信息()
            if (!$moneyq||$moneyq->is_on_sale==0){ unset($data[$k]);continue;}//商品下架或不存在，移除
            $data[$k]['original_img']=$moneyq->original_img;
            $data[$k]['commission1']=$moneyq->commission1;//商品分销佣金--一级
            $data[$k]['commission2']=$moneyq->commission2;//商品分销佣金--二级
            //判断该商品是否有规格
            if ($v->spec_key==''){//没有规格
                $data[$k]['market_price']=$moneyq->market_price;//市场价
                $data[$k]['shop_price']=$moneyq->shop_price;//本店价
            }else{//有规格
                $moneyq=SpecGoodsPriceModel::where($where)->where('key',$v->spec_key)->find();//有规格替换规格信息
                if (!$moneyq){unset($data[$k]);continue;}//商品规格不存在，移除
                $data[$k]['market_price']=$moneyq->price_tall;//市场价
                $data[$k]['shop_price']=$moneyq->price;//本店价
            }
            $data[$k]['store_count']=$moneyq->store_count;//库存
        }
//        dump($data->toArray());die();
        return $data;

    }

    /*
     * 计算购物车选中物品总价
     * $userId 用户id
     */
    public function calculate($userId)
    {

        $cart=CartModel::where('user_id','=',$userId)
            ->where('selected','=','1')//选中
            ->select();
        $money=0;
        foreach ($cart as $k=>$v){
            $where=['goods_id'=>$v->goods_id];
            //判断该商品是否有规格
            if ($v->spec_key==''){//没有规格
                $moneyq= GoodsModel::where($where)->value('shop_price');//商品本店价
            }else{//有规格
                $moneyq=SpecGoodsPriceModel::where($where)->where('key',$v->spec_key)->value('price');//规格本店价
            }
            $moneyq = $moneyq*$v->goods_num;//本店价*数量
            $money+=$moneyq;
        }
//        dump(session('user')->toArray());die();

        return $money;
    }
    /*
     * 订单确认页（去结算）
     */
    public function ordercon()
    {

        $this->emplogin();//  判断是否登陆
        //更新用户数据
        $publics=new Publics();
        $publics->upLevel();
        $getData=input();
        if (isset($getData['address_id'])){//如果有更改地址
            $where2['address_id']=$getData['address_id'];
        }else{
            $where2['is_default']=1;//没有就默认
        }
        $where['user_id']=session('user.user_id');
        //地址
        $data['address']=UserAddressModel::where($where2)->where($where)->find();


        if (!$data['address']){
            $this->redirect('User/address_list'); //没有地址重定向地址管理页
        }
        //选中购买物
        $data['cartList']=$this->shopping_trolley();//购物车选中商品的具体属性
//        dump($data['cartList']);
        //用户信息
        $data['user']=session('user');

        $where1['c2.uid']=session('user.user_id');
        $where1['c1.use_end_time'] = ['>',time()];
        $money=$this->calculate(session('user.user_id'));//订单总价（没有物流费）
        $where1['c1.condition'] = ['<=',$money];
        $couponList= CouponModel::alias('c1')->field('c1.name,c1.money,c1.condition')
            ->field('c2.*')
            ->join('tp_coupon_list c2','c2.cid = c1.id And c1.type in(0,1,2,3) And order_id = 0','inner')
            ->where($where1)
            ->select();
         $this->assign('couponList',$couponList);
        $data['total_price']=$this->total();
        return view('ordercon',$data);
    }

    /*
     *订单提交
     */
    public function addorder()
    {
        $this->emplogin();//  判断是否登陆
        $getData=input('post.');
        $where['user_id']=session('user.user_id');
        $getAddressId=input('post.address_id');//地址id
        //判断库存是否充足
        $where['user_id']=session('user.user_id');
        $cartList=$this->shopping_trolley();//购物车选中的商品
        if (!($cartList->toArray())){
            return retJson(null,201,'订单已提交');
        }
        foreach ($cartList as $k=>$v){
            if ($v->goods_num>$v->store_count){//购买数大于库存
                $goods_name=$v->goods_name .$v->spec_key_name;
                return retJson('',201,$goods_name.'库存不足');
            }
        }
        $public=new Publics();
        $commissions= $public->commission($cartList);
        $coupon_id =input('coupon_id');//优惠券id
        $total=$this->total($coupon_id);
        $Address = UserAddressModel::where($where)->find($getAddressId);//获取用户默认地址
        $insert=[
            'order_sn'=>date('YmdHis').rand(1000,9999),//订单编号
            'user_id'=>session('user.user_id'),
            'consignee'=>$Address->consignee,//收货人
            'provinceName'=>$Address->provinceName,//省
            'longitude'=>$Address->longitude,//经度
            'latitude'=>$Address->latitude,//纬度
            'address'=>$Address->region.$Address->address,//地址
            'zipcode'=>$Address->zipcode,//邮政
            'mobile'=>$Address->mobile,//收货人电话
            'commission1'=>$commissions['commission_s1'],//佣金--一级
            'commission2'=>$commissions['commission_s2'],//佣金--二级
//            'email'=>$Address->email,
//            'shipping_code'=>'shunfeng',//物流
//            'shipping_name'=>'顺丰物流',
//            'order_push'=>$min_flag_id,
//            'pay_code'=>session('user.email'),
//            'pay_name'=>session('user.email'),//支付
            'invoice_title'=>$getData['invoice_title'],//发票抬头
            'goods_price'=>$total['total_fee'],//商品总价
            'shipping_price'=>$total['shipping_price'],//邮费
            'total_amount'=>$total['total_fee']*session('user.leve')['discount']/100,//订单总价=商品总价*会员折扣/100
            'order_amount'=>$total['order_amount'],//应付金额
            'coupon_price'=>$total['coupon_price'],//优惠券抵扣
            'add_time'=>time(),//时间
            'user_note'=>$getData['user_note'],//用户备注
        ];
        $data['orderAddId']=$orderAddId=OrderModel::insertGetId($insert);//1、订单表添加

        setDatabaseDef($orderAddId,'订单添加失败');
        //更新优惠券状态
        if($coupon_id!=0){
            $wh['uid']=session('user.user_id');
            $wh['id']=$coupon_id;
            CouponListModel::where($wh)->update(['order_id'=>$data['orderAddId'],'use_time'=>time()]);
        }
        $this->orderGoodsAdd($orderAddId);//2、订单与商品表添加
        $this->orderAction($orderAddId,$getData['user_note']);//3、订单记录添加
        $cartList=CartModel::where($where) ->where('selected','=',1)->delete();//4、清除购物车选中的商品
        setDatabaseDef($cartList,'订单没有商品可以购买');
        return retJson($data,200,'提交订单成功');
    }
    /*
     *  订单与商品表添加
     * $orderAddId 订单id(一般是自增id)
     */
    public function orderGoodsAdd($orderAddId)
    {
        $where['user_id']=session('user.user_id');
        $cartList=$this->shopping_trolley();//购物车选中商品的具体属性
        foreach($cartList as $k=>$v){
            $insert=[
                'order_id'=>$orderAddId,
                'goods_id'=>$v->goods_id,
                'goods_name'=>$v->goods_name,
                'goods_sn'=>$v->goods_sn,
                'goods_num'=>$v->goods_num,//数量
                'market_price'=>$v->market_price,//市场价
                'goods_price'=>$v->shop_price,//本店价
//                'cost_price'=>$v->cost_price,
                'member_goods_price'=>$v->shop_price*(session('user.leve')['discount']/100),//商品折扣价
                'spec_key'=>$v->spec_key,
                'spec_key_name'=>$v->spec_key_name,
                'bar_code'=>$v->bar_code,//条码
                'prom_type'=>0,
                'commission1'=>$v->commission1,//佣金--一级
                'commission2'=>$v->commission2,//佣金--二级
            ];
           $addOrG=OrderGoodsModel::insert($insert);
           setDatabaseDef($addOrG,'订单与商品表添加失败'.$v->goods_name);
        }
    }
    
    /*
     * 订单记录添加
     * $orderAddId 订单id(一般是自增id)
     * $user_note 备注
     */
    public function orderAction($orderAddId,$user_note)
    {
        $insert=[

            'order_id'=>$orderAddId,
            'action_note'=>$user_note,//备注
            'log_time'=>time(),
            'status_desc'=>'用户提交订单'
        ];
        $addOrA= OrderActionModel::insert($insert);
        setDatabaseDef($addOrA,'订单记录添加失败');

    }
    /*
     * 计算订单总价、物流
     */
    public function total($coupon_id=0)
    {
        $where['user_id']=session('user.user_id');
//        $getData = input('post.');
        $data['cartList']=$this->shopping_trolley();
        //查询优惠券折扣价
        if($coupon_id !=0){
            $couwhere['c1.uid']=session('user.user_id');
            $couwhere['c1.id']=$coupon_id;
            $coupon =CouponListModel::alias('c1')->field('c2.money')
                ->join('tp_coupon c2','c1.cid = c2.id')->where($couwhere)->find();
        }else{
            $coupon['money'] =0;
        }
        //商品费、物流、总金额
        $total_price['total_fee']=0;
        $total_price['total_fee']=$this->calculate(session('user.user_id'));//计算购物车选中物品总价
        $total_price['discount']=session('user.leve')['discount']/100;//会员折扣
        $total_price['coupon_price']= $coupon['money'];//优惠券抵扣

        $total_price['shipping_price']=$this->logistics($data['cartList']);//物流
        //会员优惠价                 = 商品总价               *        会员折扣          +  邮费                        -     优惠券
        $total_price['order_amount']=$total_price['total_fee']*($total_price['discount'])+$total_price['shipping_price']- $coupon['money'];//订单最终金额(包含会员优惠）
        return $total_price;
    }
    /*
     * 支付页面
     */
    public function pay()
    {
        $this->emplogin();//  判断是否登陆

        $getData=input('get.');
//        $getData['order_id']=743;//模拟订单id
        $data['order']=OrderModel::find($getData['order_id']);//订单详情
        //支付方式
        $data['paymentList']=PluginModel::where('type','=','payment')
            ->where('status','=',1)
            ->select();
        return view('pay',$data);
    }

    
    /*
     * 支付 付款
     */
    public function getCode()
    {
        $this->emplogin();//  判断是否登陆
//        dump(session('user'));die();
        $getData=input('post.');
        if (encryption($getData['password'])!=session('user.password')){
            return retJson('','201','请填写正确密码');
        }
        //判断密码
        $getOrder=OrderModel::find($getData['order_id']);
        if (1==$getOrder->pay_status){
            return retJson('','201','订单已支付');
        }
        $getUser = UsersModel::find(session('user.user_id'));
        if ($getUser->user_money<$getOrder->order_amount){//判断余额是否足够
            return retJson('','202','余额不足');
        }

        if ($getData['pay_radio']=='balance'){//余额支付
            //1、更改订单支付状态
            $updata=[
                'order_id'=>$getData['order_id'],
                'pay_status'=>1,//订单支付状态：0未支付 1已支付
                'pay_time'=>time(),
                'pay_code'=>'',
                'pay_name'=>'余额支付',
            ];
            $setOrder = OrderModel::update($updata);
            //2、扣除余额
            $setUser = UsersModel::where(['user_id'=>session('user.user_id')])->setDec('user_money',$getOrder->order_amount);
            setDatabaseDef($setUser,'用户余额扣除失败');
            //3.订单操作记录
            $insert=[
                'order_id'=>$getData['order_id'],
                'pay_status'=>1,//支付状态
                'log_time'=>time(),
                'status_desc'=>'用户支付订单'//状态描述
            ];
            //用户资金日志添加
              $this->accountlog($getData['order_id'],1,$getOrder->order_sn,$getOrder->order_amount);

            $addOrdAct=OrderActionModel::insert($insert);//订单记录添加
            setDatabaseDef($addOrdAct,'订单记录添加失败');
            //用户累积消费金额（+）
            $pub=new Publics();
            $pub->setAccuMoney($getOrder->order_amount);//添加消费金额

            //分销商添加佣金
            return retJson('','200','支付成功');
        }
        return retJson('','201','很抱歉，本商城目前只支持余额付款');
    }
    /*
 * 计算物流费
 * $cartList 购物车勾选数据
 * $shipping  物流方式 例：'shentong'
 * 返回物流费
 */
    function logistics($cartList,$shipping='shunfeng'){
        $logistics=0;//物流
        $weight=0;//重量
        foreach ($cartList as $k=>$v){
            $getGoods = GoodsModel::find($v->goods_id);
            if (0==$getGoods->is_free_shipping){//1包邮 0不包邮
                $weight+= ($getGoods->weight*$v->goods_num);//计算重量
            }
        }
        if ($weight==0){
            return 0;
        }
        //物流规则                  //物流名                   //是否默认
        $logConfig= ShippingAreaModel::where(['shipping_code'=>$shipping,'is_default'=>1])->value('config');
        $logConfig=unserialize($logConfig);//反序列化

        // 1000 克以内的 只算个首重费
        if($weight<1000)
        {
            return 13;
        }
        // 超过 1000 克的计算方法（免费）
//        $weight = $weight - $logConfig['first_weight']; // 续重
//        $weight = ceil($weight / $logConfig['second_weight']); // 续重不够取整
//
//        $freight = $logConfig['money'] +  $weight * $logConfig['add_money']; // 首重 + 续重 * 续重费

        return 0;
    }
    /*
     * 付款成功界面
     */
    public function ordersn()
    {
        $this->emplogin();//  判断是否登陆
        $getData=input('get.');

        $data['order'] = OrderModel::find($getData['order_id']);
        return view('ordersn',$data);
    }
    /*
     * 收藏
     */
    public function collect()
    {
        $getData=input('post.');
//        dump($getData);die();
        $where=[
            'user_id'=>session('user.user_id'),
            'goods_id'=>$getData['id'],
        ];
        $getColl=GoodsCollectModel::where($where)->find();
        if ($getColl){//已收藏  删除
           $delColl= GoodsCollectModel::destroy($where);
          return setDatabase($delColl,'取消收藏');
        }else{
            $where['add_time']=time();
           $addColl=  GoodsCollectModel::insert($where);
         return setDatabase($addColl,'收藏');
        }

    }
    //获取优惠券价格
    public function cart(){
        $id = input('coupon_id');
        $where['c1.uid']=session('user.user_id');
        $where['c1.id']=$id;
        $coupon =CouponListModel::alias('c1')->field('c2.money')
            ->join('tp_coupon c2','c1.cid = c2.id')->where($where)->find();
        if (!$coupon){
            $coupon['money']=0;
            return retJson($coupon,201,'');
        }
        return retJson($coupon,200,'');


    }

    /**
     * @param $order_id 订单id
     * @param $desc     描述
     * @param $order_sn 订单编号
     * @param $user_money 用户金额
     * 用户资金日志添加
     */
    public function accountlog($order_id,$desc,$order_sn,$user_money){
        switch ($desc){
            case 1:
                $desc='下单消费';
                $user_money='-'.$user_money;
                      break;
            case 2:
                $desc='订单取消，退回'.$user_money.'元';
                $user_money='+'.$user_money;
                break;

        }
        $data =[
            'order_id'=>$order_id,
            'user_id'=>session('user.user_id'),
            'change_time'=>time(),
            'pay_points'=>0,
            'order_sn'=>$order_sn,
            'user_money'=>$user_money,
            'desc'=>$desc
            ];
        AccountLogModel::insert($data);
        return;
    }
}